import 'package:flutter/material.dart';

/// 直接把数据传递给需要的小部件
class SampleInheritedWidget3 extends StatefulWidget {
  const SampleInheritedWidget3({Key? key}) : super(key: key);

  @override
  _SampleInheritedWidget3State createState() => _SampleInheritedWidget3State();
}

class _SampleInheritedWidget3State extends State<SampleInheritedWidget3> {
  int count = 0;

  void _incrementCount() {
    setState(() {
      count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    /// 使用CounterProvider
    return CounterProvider(
        count: count,
        incrementCount: _incrementCount,
        child: Scaffold(
          appBar: AppBar(
            title: Text("InheritedWidget示例"),
          ),
          body: CounterWrapper(),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCount,
            child: Icon(Icons.add),
          ),
        ));
  }
}

/// 数据提供控件
class CounterProvider extends InheritedWidget {
  final int count;
  final VoidCallback incrementCount;
  final Widget child;

  CounterProvider(
      {required this.count, required this.incrementCount, required this.child})
      : super(child: child);

  /// 获取CounterProvider
  static CounterProvider of(BuildContext context) {
    final CounterProvider? onInheritedWidgetOfExactType =
        context.dependOnInheritedWidgetOfExactType<CounterProvider>();
    return onInheritedWidgetOfExactType!;
  }

  @override
  bool updateShouldNotify(covariant CounterProvider oldWidget) {
    return oldWidget.count != oldWidget.count;
  }
}

class CounterWrapper extends StatelessWidget {
  CounterWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: CounterWiget(),
    );
  }
}

class CounterWiget extends StatelessWidget {
  CounterWiget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var counterProvider = CounterProvider.of(context);
    return Center(
      child: ActionChip(
        label: Text("${counterProvider.count}"),
        onPressed: counterProvider.incrementCount,
      ),
    );
  }
}
